package com.wt.springsamples.security.exception;

import com.alibaba.fastjson.JSON;
import com.wt.springsamples.common.ApiResult;
import com.wt.springsamples.common.ApiResultCodeEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 没有正确携带Jwt认证所需要的请求头信息
 * 请求头名称：Authorization
 * 请求头值：Bearer XXXX
 * 请求头的值需要是正确JwtToken格式，否则也会进入该回调接口
 */
public class GlobalAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        System.out.println("进入GlobalAuthenticationEntryPoint的commence方法,表示认证失败");
//        Cookie[] cookies = request.getCookies();
//        Cookie cookie = new Cookie("N_JSESSIONID",request.getSession().getId());
//        cookie.setPath("/");
//        cookie.setDomain("localhost:8081");//必须和当前服务器是统一地址，非同源策略时浏览器会阻止其自动保存
//        cookie.setSecure(true);
//        response.addCookie(cookie);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        //输出结果
        ApiResult<String> result = ApiResult.build(ApiResultCodeEnum.LOGIN_AUTH.getCode(),ApiResultCodeEnum.LOGIN_AUTH.getMessage());
        response.getWriter().write(JSON.toJSONString(result));
    }
}
